<template>
<div class="rx-mobile-button-box">
    <div class="rx-mobile-grid-box">
        <div class="rx-mobile-grid-toolbar">
            <a-button type="primary" @click="addMobileButton">{{i18n('isButton.addButton','新增按钮')}}</a-button>
            <a-button class="rx-modile-button" v-if="showDefaultButton" @click="getDefMobileBtns">{{i18n('isButton.addAllDefaults','新增全部默认')}}</a-button>
            <a-button class="rx-modile-del" @click="removeRow">{{i18n('isButton.deleteButton','删除按钮')}}</a-button>
            <a-button class="rx-modile-button" @click="upRow">{{i18n('isButton.upward','向上')}}</a-button>
            <a-button class="rx-modile-button" @click="downRow">{{i18n('isButton.downward','向下')}}</a-button>
            <a-button class="rx-modile-button" @click="topUp">{{ i18n_('list.topUp', '置顶') }}</a-button>
            <a-button class="rx-modile-button" @click="bottomUp">{{ i18n_('list.bottomUp', '置底') }}</a-button>
        </div>
        <div class="rx-mobile-grid-container">
            <rx-grid
                class="table_toolBar"
                ref="table_mobileBtn"
                :dataSource="mobileBtns"
                :columns="mobileBtnColumns"
                :allowRowSelect="true"
                :multiSelect="true"
                :showPage="false"
                :bordered="true"
                :heightAuto="true"
            >
                <span slot="btnLabel" slot-scope="{text,record,index}">
                    <a-input v-model="record.btnLabel" @change="updateI18nName(record,'btnLabel')">
                        <my-icon slot="addonAfter" type="iconearth-full" @click="editI18nName(record,'btnLabel')"/>
                    </a-input>
                </span>
                <span slot="btnName" slot-scope="{text,record,index}">
                    <a-input v-model="record.btnName" />
                </span>
                <span slot="btnClick" slot-scope="{text,record,index}">
                    <template v-if="record.isDefault">{{record.btnClick}}</template>
                    <template v-else>
                        <a-input v-model="record.btnClick" />
                    </template>
                </span>
                <span slot="btnType" slot-scope="{text,record,index}">
                    <template v-if="record.isDefault">
                      {{record.btnType_name}}
                    </template>
                    <template v-else>
                        <a-radio-group v-model="record.btnType" @change="changeBtnType(record)">
                            <a-radio  value="row">{{i18n('isButtonSizeMap.row','行内')}}</a-radio>
                            <a-radio  value="list">{{$comi18('rxDialog.dialogList', '列表')}}</a-radio>
                        </a-radio-group>
                    </template>
                </span>
                <span slot="btnPreCond" slot-scope="{text,record,index}">
                    <a-button size="small" @click="openPreCondSetting(record)">{{i18n('list.config','配置')}}</a-button>
                    <span v-if="record.isSetedPreCondition" class="is-seted"><i
                        class="iconfont iconsuccess_fill is-seted"></i>{{i18n('list.configured','已配')}}</span>
                    <a-icon v-if="record.isSetedPreCondition" type="delete" style="margin-left: 10px;" @click="clearPreCondition(record,'btnPreCond')"/>
                </span>
              <span slot="btnShow" slot-scope="{text,record,index}">
                    <a-button size="small" @click="openShowSetting(record)">{{i18n('list.config','配置')}}</a-button>
                    <span v-if="record.isSetedShowCondition" class="is-seted"><i
                        class="iconfont iconsuccess_fill is-seted"></i>{{i18n('list.configured','已配')}}</span>
                    <a-icon v-if="record.isSetedShowCondition" type="delete" style="margin-left: 10px;" @click="clearPreCondition(record,'btnShow')"/>
                </span>
            </rx-grid>
        </div>
    </div>
</div>
</template>

<script>
import {RxGrid, Util,Dialog,I18Parse} from "@lowcode/jpaas-common-lib";
import FormMobileListBtnEdit from "@/views/modules/form/core/formPermission/FormMobileListBtnEdit";
import FormBoListButtonPreConfig from "@/views/modules/form/core/FormBoListButtonPreConfig";
import FormBolistBtnShow from "@/views/modules/form/core/FormBolistBtnShow";

export default {
    name: "mobileButton",
    props:["pkId"],
    components:{
        RxGrid
    },
    data(){
        return {
            vm:null,
            activeKey:'mobileBtn',
            gridData:[],
            mobileBtns:[],
            selectedRowKeys:[],
            selectedRows:[],
            mobileBtnColumns:[
                {title: this.i18n('form.buttonName','按钮名称'), dataIndex: 'btnLabel', scopedSlots: {customRender: 'btnLabel'}},
                {title: this.i18n('form.buttonMark','按钮标识'), dataIndex: 'btnName',  scopedSlots: {customRender: 'btnName'}},
                {title: this.i18n('form.eventFunc','事件函数'), dataIndex: 'btnClick',  scopedSlots: {customRender: 'btnClick'}},
                {title: this.i18n('form.typeButton','按钮类型'), dataIndex: 'btnType', scopedSlots: {customRender: 'btnType'}},
                {title: this.i18n('form.Preconditions','前置条件'), dataIndex: 'btnPreCond', scopedSlots: {customRender: 'btnPreCond'}},
                {title: this.i18n('form.displayCon','显示条件'), dataIndex: 'btnShow', scopedSlots: {customRender: 'btnShow'}},
            ],
            defMobileBtns:[],
            isI18nLang:process.env.VUE_APP_ISLANGUAGE,
            i18nDefault:process.env.VUE_APP_LANGUAGE,
            i18nCurrent:"",
            i18nJson:{},
            i18nMenuName:"",
            defaultBtnI18ns:{
                "onMobileAdd": {
                    "zh-CN": "新增",
                    "en-US": "Add",
                    "ja-JP": "追加",
                    "es-ES": "Añadir"
                },
                "onMobileEdit": {
                    "zh-CN": "编辑",
                    "en-US": "Edit",
                    "ja-JP": "編集",
                    "es-ES": "Editar"
                },
                "onMobileRemove": {
                    "zh-CN": "删除",
                    "en-US": "Delete",
                    "ja-JP": "削除",
                    "es-ES": "Eliminar"
                },
                "onMobileDetail": {
                    "zh-CN": "明细",
                    "en-US": "Details",
                    "ja-JP": "詳細",
                    "es-ES": "Detalles"
                }
            }
        }
    },
    computed:{
        showDefaultButton(){
            if(this.vm && this.vm.mdl && this.vm.mdl.isDialog=='NO' ){
                return true;
            }
            return false;
        }
    },
    created(){
        this.getCurrentI18n();
    },
    methods:{
        i18n(name,text,key){
            return this.$ti18(name,text,"FormCalendarView",key);
        },
        i18n_(name, text, key) {
            return this.$ti18(name, text, "formBoListDialog", key);
        },
        setData(vm,data){
            this.vm=vm;
            this.mobileBtns.push(...(data.mobileButton || []));
            this.initBtns(vm.mdl);
        },
        getCurrentI18n(){
            this.i18nCurrent= window.localStorage.getItem("language");
            if(!this.i18nCurrent){
                this.i18nCurrent=this.i18nDefault;
            }
        },
        editI18nName(record,col) {
            let self_ = this;
            let row =record;
            let conifg = {
                curVm: this,
                widthHeight: ['600px', '400px'],
                data: {
                    i18nJson: this.getI18nJson(row,col)
                }
            }
            Dialog.openI18nDialog(conifg, function (action, data) {
                self_.$set(row, col, data[self_.i18nCurrent]);
                self_.$set(row, "i18nJson", JSON.stringify(data));
            });
        },
        getI18nJson(row,col){
            let i18nJson={};
            let i18nConf =row.i18nJson;
            if(i18nConf){
                i18nJson=JSON.parse(i18nConf);
                let val=i18nJson[this.i18nCurrent];
                if(!val){
                    i18nJson[this.i18nCurrent]=row[col];
                }
            }else {
                i18nJson[this.i18nCurrent] = row[col];
                i18nJson[this.i18nDefault] = row[col];
            }
            return i18nJson;
        },
        updateI18nName(record, col) {
            let i18nJson=this.getI18nJson(record,col);
            i18nJson[this.i18nCurrent]=record[col];
            this.$set(record, "i18nJson", JSON.stringify(i18nJson));
        },
        getData(){
            var data=this.$refs["table_" + this.activeKey].getData();
            if(this.isNotUnionBtnName(data)){
                return {success:false,message:this.i18n('notSetSame','不可设置同标识按钮！')};
            }
            return {success:true,data:{mobileButton:data}};
        },
        isNotUnionBtnName(ary){
            var arr=[];
            for(var i=0;i<ary.length;i++){
                if(arr.includes(ary[i].btnName)){
                    return true;
                }
                arr.push(ary[i].btnName);
            }
            return false;
        },
        initBtns(value){
            let { key } = value ;
            this.defMobileBtns=[
                {btnId:1,btnLabel:this.$ti18('rxList.add', '新增'),isDefault:true, btnType:'list',btnType_name:this.$comi18('rxDialog.dialogList', '列表'),btnName:key+'_MobileAdd',btnClick:'onMobileAdd',permission:{label:this.i18n('all','所有人'),value:"everyone"}},
                {btnId:2,btnLabel:this.$ti18('rxList.editBtn','编辑'),btnType:'row',isDefault:true,btnType_name:this.i18n('isButtonSizeMap.row','行内'),btnName:key+'_MobileEdit',btnClick:'onMobileEdit',permission:{label:this.i18n('all','所有人'),value:"everyone"}},
                {btnId:3,btnLabel:this.$ti18('rxList.delBtn','删除'),btnType:'row',isDefault:true,btnType_name:this.i18n('isButtonSizeMap.row','行内'),btnName:key+'_MobileRemove',btnClick:'onMobileRemove',permission:{label:this.i18n('all','所有人'),value:"everyone"}},
                {btnId:4,btnLabel:this.$ti18('rxList.detailBtn','明细'),btnType:'row',isDefault:true,btnType_name:this.i18n('isButtonSizeMap.row','行内'),btnName:key+'_MobileDetail',btnClick:'onMobileDetail',permission:{label:this.i18n('all','所有人'),value:"everyone"}}
            ]
        },
        loadInitI18nVal(obj,text){
            if(!obj.i18nJson){
                let i18nJson = {};
                i18nJson[this.i18nCurrent]=obj[text];
                obj.i18nJson=JSON.stringify(i18nJson);
                return;
            }
            let i18nJson =JSON.parse(obj.i18nJson);
            let val=i18nJson[this.i18nCurrent];
            if(!val){
                return;
            }
            obj[text]=val;
        },
        addMobileButton(){
            //添加按钮
            this.addRow( {btnId:Util.randomId(),btnLabel:'',isDefault:false,btnType:'row',btnType_name:this.i18n('isButtonSizeMap.row','行内'),btnName:'',btnClick:'',permission:{label:this.i18n('all','所有人'),value:"everyone"}})
        },
        addRow(row){
            this.$refs["table_" + this.activeKey].addRow(row);
        },
        changeBtnType(record){
            record.btnType_name=record.btnType=="row"?this.i18n('isButtonSizeMap.row','行内'):this.$comi18('rxDialog.dialogList', '列表');
        },
        getDefMobileBtns(){
            for (let btn of this.defMobileBtns){
                this.loadInitI18nVal(btn,'btnLabel');
                this.setOtherDefaultI18nVal(btn,'btnLabel')
            }
            let btnsTree =Util.listToTree(this.defMobileBtns,'btnId');
            for (let i = 0; i < btnsTree.length; i++) {
                let tmpBtns = this.mobileBtns.filter((item) => {
                    return btnsTree[i].btnId == item.btnId
                })
                if (tmpBtns.length > 0) {
                    continue
                }
                this.mobileBtns.push(btnsTree[i])
            }
        },
        //设置中文、英文默认值
        setOtherDefaultI18nVal(btn){
            let langs=I18Parse.handleLanList();
            if(!langs || langs.length==0){
                return;
            }
            let self_=this;
            langs.forEach(lang=>{
                if(lang!=this.i18nCurrent){
                    let langVal=self_.defaultBtnI18ns[btn.btnClick];
                    if(langVal){
                        let i18nJson= JSON.parse(btn.i18nJson);
                        i18nJson[lang]=langVal[lang];
                        btn.i18nJson=JSON.stringify(i18nJson);
                    }
                }
            })

        },
        removeRow() {
            var table=this.$refs["table_" + this.activeKey];
            table.removeRows();
            table.selectedRowKeys=[];
            table.selectedRows=[];
            this.$forceUpdate();
        },
        upRow() {
            this.$refs["table_" + this.activeKey].moveUp();
        },
        downRow() {
            this.$refs["table_" + this.activeKey].moveDown();
        },
        setMobileBtnAuth(){
            var self=this;
            var config={
                curVm: self,
                widthHeight: ['800px', '450px'],
                component:FormMobileListBtnEdit,
                title:self.i18n('form.powerConfiguration','权限配置'),
                data:{mainData:self.mobileBtns}
            };
            Util.open(config,function(action,data){
                if(action!='ok')return;
                self.mobileBtns=data;
            });
        },
      openShowSetting(record){
        var config = {
          curVm: this,
          max:true,
          component: FormBolistBtnShow,
          data: {
            pkId: this.pkId,
            script: record.btnShow,
            isTreeDialog : true
          },
          title: this.i18n('form.displayCon','显示条件')
        };
        Util.open(config, function (action, data) {
          if (action == "ok") {
            record.btnShow = data;
            record.isSetedShowCondition = true
          }

        });
      },
        openPreCondSetting(record) {
            var config = {
                curVm: this, widthHeight: ['1000px', '730px'],
                component: FormBoListButtonPreConfig,
                data: {
                    config: record.btnPreCond, pkId: this.pkId
                },
                title: this.i18n('form.preConfig','按钮前置条件配置')
            };
            Util.open(config, function (action, data) {
                if (action == "ok") {
                    record.btnPreCond = data;
                    record.isSetedPreCondition = true
                }
            });
        },
        clearPreCondition(record,type){
            this.$confirm({
                title: this.$ti18('rxMsa.tipsInfo','提示信息'),
                content: this.i18n('sureDelete','确认删除配置吗?'),
                onOk() {
                  if(type=='btnPreCond'){
                    record.btnPreCond="";
                    record.isSetedPreCondition=false;
                  }else {
                    record.btnShow = '';
                    record.isSetedShowCondition = false
                  }

                },
                onCancel() {},
                okText:this.$ti18('rxForm.ackBtn','确认'),
                cancelText:this.$ti18('rxForm.cancelBtn','取消')
            });
        },
        topUp(){
            this.$refs.table_mobileBtn.moveTopUp();
        },
        bottomUp(){
            this.$refs.table_mobileBtn.moveBottomUp();
        },
    }
}
</script>

<style scoped>
.rx-mobile-grid-toolbar{
    padding-bottom:10px;
}
.rx-mobile-grid-toolbar button{
    margin-right: 6px;
}
.rx-mobile-grid-toolbar .rx-modile-button{
    background-color: #f5f7fa;
}
.rx-mobile-grid-toolbar .rx-modile-button:focus,
.rx-mobile-grid-toolbar .rx-modile-button:active{
    border-color: #d9d9d9;
    color: rgba(0,0,0,.65);
}
.rx-mobile-grid-toolbar .rx-modile-del:hover{
    background-color: #ff4d4f;
    border-color: #ff4d4f;
    color: #fff;
}
.rx-mobile-grid-box{
    margin-bottom: 40px;
}
</style>